package com.mk.admin.controller;

import cn.hutool.core.util.IdUtil;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.vo.LoginVo;
import com.mk.admin.service.AdminService;
import com.mk.admin.util.CodeEnum;
import com.mk.admin.util.CodeTool;
import com.mk.admin.util.MD5;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "登录")
public class LoginController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    @ApiOperation(value = "登录,可用账号或手机号+密码登录", notes = "登录成功后,返回当前用户对应的菜单，即可根据当前的账号查询对应的用户信息，如根据账号查询对应的医生信息")
    @SuppressWarnings("all")
    public ResultDto login(@RequestBody LoginVo vo) {
        String code = (String) redisTemplate.opsForValue().get(vo.getUuid());
//        redisTemplate.delete(vo.getUuid());
        if (StringUtils.isEmpty(code)) {
            return ResultDto.error("验证码不存在或者已过期");
        }
        if (!code.equals(vo.getCode())) {
            return ResultDto.error("验证码错误");
        }
        vo.setPassword(MD5.encoderByMd5(vo.getPassword()));
        return adminService.login(vo);
    }

    @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    @SuppressWarnings("all")
    public ResultDto getCode() {
        // 获取运算的结果
        Captcha captcha = new CodeTool().getCaptcha();
        String uuid = IdUtil.simpleUUID();
        // 当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == CodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        redisTemplate.opsForValue().set(uuid, captchaValue);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {
            {
                put("img", captcha.toBase64());
                put("uuid", uuid);
            }
        };
        return ResultDto.data(imgResult);
    }

    @PostMapping("/loginOut")
    @ApiOperation("退出登录")
    @SuppressWarnings("all")
    public ResultDto loginOut(@RequestBody LoginVo vo) {
        redisTemplate.delete(vo.getUuid());
        return ResultDto.data("退出成功");
    }
}
